package com.sgb.kjwl.view.ui.adapter.home;

import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sgb.kjwl.BR;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.databinding.ItemMapAndListVohiclehallBinding;
import com.sgb.kjwl.model.entity.transport.SingleItemConstant;
import com.sgb.kjwl.model.entity.transport.VehicleHallMapEntity;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.view.entity.PermissionEntity;
import com.sgb.kjwl.utils.LogisticsPermissionHelper;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.util.PermissionCheckUtil;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.ui.activity.self.logistics.InquiryActivity;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.im.immodel.IMUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author: 杨畔
 * @date: 3/3/21 8:10 PM
 * @Description: 车辆大厅适配器
 */
public class CarsHallListAndMapAdapter extends BaseMultiItemQuickAdapter<VehicleHallMapEntity, BaseViewHolder> {
    /**
     * Same as QuickAdapter#QuickAdapter(Context,int) but with
     * some initialization data.
     *
     * @param data A new list is created out of this one to avoid mutable list
     */
    public CarsHallListAndMapAdapter(List<VehicleHallMapEntity> data) {
        super(data);
        //车辆类别
        addItemType(SingleItemConstant.TYPE_ONE, R.layout.item_map_and_list_vohiclehall);

    }

    @Override
    protected void convert(BaseViewHolder helper, VehicleHallMapEntity item) {
        initCarInfo(helper, item);
    }

    /**
     * 设置车辆信息
     */
    private void initCarInfo(BaseViewHolder helper, VehicleHallMapEntity entity) {
        //设置dataBinding数据
        ItemMapAndListVohiclehallBinding binding = DataBindingUtil.bind(helper.itemView);
        if (binding == null) return;
        binding.setVariable(BR.viewModel, entity);
        binding.executePendingBindings();

        StringBuilder builder = new StringBuilder();
        if (!TextUtils.isEmpty(entity.getCarTypeName())) {
            builder.append(entity.getCarTypeName()).append("\u0020");
        }
        if (!TextUtils.isEmpty(entity.getHeightHurdle())) {
            builder.append("栏高");
            builder.append(NumberUtil.trim0(entity.getHeightHurdle()));
            builder.append("米/");
        }
        if (!TextUtils.isEmpty(entity.getCarLenName())) {
            builder.append(entity.getCarLenName());
        }
        if (entity.getWeight() != null) {
            builder.append("\u0020");
            builder.append(NumberUtil.trim0(entity.getWeight()));
            builder.append("吨");
        }

        if (entity.getIsDumper() != null) {
            builder.append("\u0020");
            builder.append(entity.getIsDumper() == 1 ? "自卸" : "非自卸");
        }
        binding.titleView.setText(builder.toString());
        //没有位置信息时隐藏
        if (TextUtils.isEmpty(entity.getProvinceName()) && TextUtils.isEmpty(entity.getCityName()) && TextUtils.isEmpty(entity.getDistrictName())) {
            binding.priceView.setVisibility(View.GONE);
        } else {
            binding.priceView.setVisibility(View.VISIBLE);
            binding.priceView.setText(String.format("%s%s%s", entity.getProvinceName(), entity.getCityName(), entity.getDistrictName()));
        }

        if (entity.getDistance() == null) {
            binding.tvDistance.setText("");
        } else {
            binding.tvDistance.setText(entity.getDistance() < 1000 ? "距您 1km以内" : "距您 " + NumberUtil.trim0(entity.getDistance() / 1000) + "km");
        }

        binding.llPhone.setOnClickListener(v -> {
            if (UserOperating.getInstance().isNotLogged(mContext)) {
                return;
            }
            if(entity!=null&&!UserOperating.getInstance().IsAuth(mContext,entity.getAuthTime())){
                return;
            }
            invitationClick(entity);
        });

        binding.llChat.setOnClickListener(v -> {
            if (UserOperating.getInstance().isNotLogged(mContext)) {
                return;
            }
            if(entity!=null&&!UserOperating.getInstance().IsAuth(mContext,entity.getAuthTime())){
                return;
            }
            chatClick(entity);
        });

        binding.llInquiry.setOnClickListener(v -> {
            if (UserOperating.getInstance().isNotLogged(mContext)) {
                return;
            }
            if(entity!=null&&!UserOperating.getInstance().IsAuth(mContext,entity.getAuthTime())){
                return;
            }
            requestPermissions(entity);
        });

        RequestOptions requestOptions = null;
        if (entity.getTerminal() == 1) {
            requestOptions = new RequestOptions()
                    .placeholder(R.mipmap.icon_company_default)//图片加载出来前，显示的图片
                    .fallback(R.mipmap.icon_company_default) //url为空的时候,显示的图片
                    .error(R.mipmap.icon_company_default);//图片加载失败后，显示的图片
        } else if (entity.getTerminal() == 2) {
            requestOptions = new RequestOptions()
                    .placeholder(R.mipmap.icon_team_default_1)//图片加载出来前，显示的图片
                    .fallback(R.mipmap.icon_team_default_1) //url为空的时候,显示的图片
                    .error(R.mipmap.icon_team_default_1);//图片加载失败后，显示的图片
        } else if (entity.getTerminal() == 3) {
            requestOptions = new RequestOptions()
                    .placeholder(R.drawable.geren_person_touxiang)//图片加载出来前，显示的图片
                    .fallback(R.drawable.geren_person_touxiang) //url为空的时候,显示的图片
                    .error(R.drawable.geren_person_touxiang);//图片加载失败后，显示的图片
        }

        if (TextUtils.isEmpty(entity.getRoleName())) {
            binding.teamInfoLayout.setVisibility(View.GONE);
        } else {
            binding.teamInfoLayout.setVisibility(View.VISIBLE);
            binding.teamName.setText(entity.getRoleName());
            Glide.with(mContext).load(entity.getImg()).apply(requestOptions).into(binding.teamImg);
        }
    }

    /**
     * 获取权限
     * @param entity
     */
    public void requestPermissions(VehicleHallMapEntity entity) {
        DialogHelper.showProgressDialog(mContext, "数据获取中...").setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getLogisticsAPI().getLogisticsPermissions().enqueue(new ICallBack<BaseEntity<PermissionEntity>>() {
            @Override
            public void onSuccess(BaseEntity<PermissionEntity> data) {
                if(data.isSuccess()){
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COM_TYPE, data.getData().getUserType());
                    UserOperating.getInstance().setUserInfo(data.getData());
                    inquiryClick(entity);
                }
            }
        });
    }

    /**
     * 询价
     */
    private void inquiryClick(VehicleHallMapEntity entity) {
        if (entity == null)
            return;
        if (UserOperating.getInstance().isNotLogged(mContext)) {
            return;
        }
        if (UserOperating.getInstance().isNotOpenFundAccount(mContext, PermissionCheckUtil.KEY_WODEXUNJIA)) {
            return;
        }
        getInquiryPermissions(entity);
    }


    /**
     * 查询询价权限
     * @param entity
     */
    public void getInquiryPermissions(VehicleHallMapEntity entity) {
        if (!TextUtils.isEmpty(entity.getDriverAuthNo())) {
            NewAPIManager.getInstance().getLogisticsAPI().getInquiryPermissions(entity.getDriverAuthNo(), "").enqueue(new ICallBack<BaseEntity<Boolean>>() {
                @Override
                public void onSuccess(BaseEntity<Boolean> data) {
                    if(data.isSuccess()){
                        if (data.getData()) {
                            //去询价界面
                            InquiryActivity.startCarInquiry(mContext, String.valueOf(entity.getDriverAuthNo()), entity.getTelphone());
                        } else {
                            MToast.showToast(mContext, "不能对自己发布的车辆进行询价！");
                        }
                    }
                }
            });
        }
    }

    /**
     * 聊天
     */
    private void chatClick(VehicleHallMapEntity entity) {
        if (entity != null && !TextUtils.isEmpty(entity.getDriverCreateIm())) {
            IMUtils.getInstance().buildSingleTalking(entity.getDriverCreateIm());
        }
    }

    /**
     * 邀请
     */
    private void invitationClick(VehicleHallMapEntity entity) {
        if (!TextUtils.isEmpty(entity.getCompanyNo())) {
            LogisticsPermissionHelper.getInstance().checkPermissionToInvite(mContext, entity.getCompanyNo(), 1);
        } else {
            LogisticsPermissionHelper.getInstance().checkPermissionToInvite(mContext, "", 0);
        }
    }

    private void showTelDialog(String phone) {
        new RoundDialog.Builder(mContext)
                .title("确认呼叫")
                .content(phone)
                .confirm("拨打")
                .cancelable(false)
                .confirmCallback(v -> {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + phone);
                    intent.setData(data);
                    mContext.startActivity(intent);
                })
                .show();
    }

}
